import customtkinter as ctk
import requests
from PIL import Image
import io


class OrderDialog(ctk.CTkToplevel):
    def __init__(self, parent, order: dict, controller):
        super().__init__(parent)
        self.order = order
        self.controller = controller
        self.title('确认发货' if self._show_confirm() else '订单详情')
        self.geometry('800x650')
        self._init_ui()
        try:
            self.transient(self.master)
            self.attributes('-topmost', True)
            self.update_idletasks()
            pw = self.master.winfo_width()
            ph = self.master.winfo_height()
            px = self.master.winfo_rootx()
            py = self.master.winfo_rooty()
            sw = self.winfo_width()
            sh = self.winfo_height()
            x = px + (pw - sw) // 2
            y = py + (ph - sh) // 2
            self.geometry(f"{sw}x{sh}+{x}+{y}")
            self.focus()
        except Exception:
            pass

    def _show_confirm(self) -> bool:
        state = self.order.get('state', 0)
        try:
            s = str(state)
        except Exception:
            s = '0'
        return s == '2' and bool(self.order.get('order_no'))

    def _row(self, parent, k, v):
        row = ctk.CTkFrame(parent)
        ctk.CTkLabel(row, text=k + ':').pack(side='left', padx=10, pady=6)
        lab = ctk.CTkLabel(row, text=v)
        lab.pack(side='left', padx=10, pady=6)
        return row

    def _init_ui(self):
        frm = ctk.CTkFrame(self)
        frm.pack(fill='both', expand=True, padx=10, pady=10)

        content = ctk.CTkScrollableFrame(frm)
        content.pack(fill='both', expand=True)

        buyer_name = self.order.get('buyer_nickname', '未知')
        order_no = str(self.order.get('order_no') or '')
        film_name = self.order.get('film_name', '未知')
        seat_info = self.order.get('seat') or self.order.get('seat_info') or ''
        cinema_name = self.order.get('cinema_name', '未知')
        hall_name = self.order.get('hall_name', '未知')
        city = self.order.get('city_name') or ''
        district = self.order.get('district_name') or ''
        city_district = f'{city}/{district}' if city or district else ''
        show_time = self.order.get('show_time', '未知')
        m_price = self.order.get('market_price') or self.order.get('market_price_single')
        s_price = self.order.get('api_price') or self.order.get('api_price_single') or self.order.get('special_price')
        market_price = f"{(m_price/100):.2f}" if isinstance(m_price, (int, float)) else (m_price if m_price else '')
        special_price = f"{(s_price/100):.2f}" if isinstance(s_price, (int, float)) else (s_price if s_price else '')
        state = self.order.get('state', 0)
        status_map = {
            '0': '询价', '1': '待付款', '2': '已付款待发货', '3': '已发货待确认', '4': '已发货已收货'
        }
        if isinstance(state, int):
            status_str = status_map.get(str(state), f'未知状态({state})')
        elif isinstance(state, str) and state.isdigit():
            status_str = status_map.get(state, f'未知状态({state})')
        else:
            status_str = '未知状态'

        items = [
            ('买家名称', buyer_name),
            ('订单编号', order_no),
            ('电影名称', film_name),
            ('座位信息', seat_info),
            ('影院名称', cinema_name),
            ('影厅名称', hall_name),
            ('地区信息', city_district),
            ('放映时间', show_time),
            ('订单状态', status_str),
            ('原价', market_price),
            ('特价', special_price),
        ]
        for k, val in items:
            self._row(content, k, str(val)).pack(fill='x')
            ctk.CTkSeparator(content, orientation='horizontal').pack(fill='x', padx=10, pady=6)

        if self.order and self.order.get('state') == 4 and self.order.get('ticket_json'):
            try:
                import json
                tickets = json.loads(self.order.get('ticket_json'))
            except Exception:
                tickets = [{'img': self.order.get('ticket_json', ''), 'code': ''}]
            ctk.CTkLabel(content, text='票据信息').pack(anchor='w', padx=10, pady=6)
            for t in tickets:
                img_url = t.get('img', '') if isinstance(t, dict) else ''
                code = t.get('code', '') if isinstance(t, dict) else ''
                if img_url:
                    try:
                        r = requests.get(img_url, timeout=10)
                        im = Image.open(io.BytesIO(r.content))
                        im.thumbnail((760, 760))
                        from customtkinter import CTkImage
                        ctki = CTkImage(light_image=im, dark_image=im, size=im.size)
                        imgLab = ctk.CTkLabel(content, image=ctki, text='')
                        imgLab.pack(padx=10, pady=10)
                    except Exception:
                        ctk.CTkLabel(content, text=f'图片URL: {img_url}').pack(anchor='w', padx=10, pady=6)
                if code:
                    ctk.CTkLabel(content, text=f'取票码: {code}').pack(anchor='w', padx=10, pady=6)

        btnRow = ctk.CTkFrame(frm)
        if self._show_confirm():
            ok = ctk.CTkButton(btnRow, text='确认发货', command=lambda: self._confirm(order_no))
            ok.pack(side='left', padx=10, pady=10)
            cancel = ctk.CTkButton(btnRow, text='取消', command=self._close)
            cancel.pack(side='left', padx=10, pady=10)
        else:
            close = ctk.CTkButton(btnRow, text='关闭', command=self._close)
            close.pack(side='left', padx=10, pady=10)
        btnRow.pack(fill='x')

    def _confirm(self, order_no: str):
        try:
            self.controller.confirm_shipment(order_no)
        except Exception:
            pass
        self._close()

    def _close(self):
        try:
            self.destroy()
        except Exception:
            pass

    def show(self):
        self.grab_set()
        self.wait_window(self)

